package com.geek.chat.common.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Module ID: </br>
 * Comments：本类为工具通用类</br>
 * Create Date: 2011-04-07
 * @author B_JIANQIANG
 */
public class Utils
{
	public static void main(String[] args) {
		String s = null;
		if(Utils.isNotNull(s)){
			System.out.println("s 不为空串， s="+s);
		} else {
			System.out.println("s 为空字符串");
		}
		
		System.out.println(Utils.isNumeric("12ds"));
	}
	
   /* public static String getLocalAdress(IoSession session)
    {
        if(session==null)
            return null;
        String _localAdress = session.getLocalAddress().toString().replace("/","");
        return _localAdress;
        
    }*/
    public static String getDateString() {
	        SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");
	        SimpleDateFormat dd=new SimpleDateFormat("dd");
	        String yearMonth=sf.format(new Date());
	        String day=dd.format(new Date());
	        return yearMonth+"/"+day+"/";
	    }
	/**
	 * check String is null or not;
	 * 
	 * @param checkStr
	 * @return boolean
	 */
	public static boolean isNull(String checkStr) {
		return checkStr == null || checkStr.trim().length() == 0
				|| checkStr.trim().equalsIgnoreCase("null");
	}
	
	/**
	 * check String is null or not;
	 * 
	 * @param checkStr
	 * @return boolean
	 */
	public static boolean isNotNull(String checkStr) {
		return checkStr != null && checkStr.trim().length() > 0
				&& !checkStr.trim().equalsIgnoreCase("null");
	}

	/**
	 * parse String to int
	 * 
	 * @param intStr
	 * @param defaultInt
	 * @return int
	 */
	public static int parseInt(String intStr, int defaultInt) {
		try {
			return Integer.parseInt(intStr);
		} catch (Exception e) {
			return defaultInt;
		}
	}

	/**
	 * parse String to int default is 0
	 * 
	 * @param intStr
	 * @return int
	 */
	public static int parseInt(String intStr) {
		return parseInt(intStr, 0);
	}

	/**
	 * check String is int
	 * 
	 * @param str
	 * @return boolean
	 */
	public static boolean isInt(String str) {
		Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}
	
	public static boolean isNumeric(String value){  
        String regex = "^(-?[1-9]\\d*\\.?\\d*)|(-?0\\.\\d*[1-9])|(-?[0])|(-?[0]\\.\\d*)$";  
        return value.matches(regex);  
    }  
	
	public static boolean isBoolean(String value){
		return (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"));
	}

	/**
	 * @param str
	 * @param charset
	 * @return String
	 */
	public static String encodeStr(String str, String charset) {
		if (isNull(str)) {
			return str;
		} else {
			try {
				return new String(str.getBytes(charset));
			} catch (Exception e) {
				return str;
			}
		}
	}

	/**
	 * trim String
	 * 
	 * @param str
	 * @return String
	 */
	public static String trimStr(String str) {
		if (null != str)
			return str.trim();
		else
			return str;
	}

	/**
	 * get substring term from src
	 * 
	 * @param src
	 * @param term
	 * @return String
	 */
	public static String subBefore(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.indexOf(term);
			return index >= 0 ? src.substring(0, index) : src;
		}
	}

	/**
	 * get substring after term from src
	 * 
	 * @param src
	 * @param term
	 * @return string
	 */
	public static String subAfter(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.indexOf(term);
			return index >= 0 ? src.substring(index + term.length()) : src;
		}
	}

	/**
	 * get substring last before term from src
	 * 
	 * @param src
	 * @param term
	 * @return string
	 */
	public static String subLastBefore(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.lastIndexOf(term);
			return index >= 0 ? src.substring(0, index) : src;
		}
	}

	/**
	 * get substring last after term from src
	 * 
	 * @param src
	 * @param term
	 * @return string
	 */
	public static String subLastAfter(String src, String term) {
		if (src == null || term == null) {
			return null;
		} else {
			int index = src.lastIndexOf(term);
			return index >= 0 ? src.substring(index + term.length()) : src;
		}
	}

	/**
	 * 获取字符串区间
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static String substring(String str, int start) {
		if (str == null) {
			return null;
		}

		// handle negatives, which means last n characters
		if (start < 0) {
			start = str.length() + start; // remember start is negative
		}

		if (start < 0) {
			start = 0;
		}
		if (start > str.length()) {
			return "";
		}

		return str.substring(start);
	}

	/**
	 * 获取字符串区间
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static String substring(String str, int start, int end) {
		if (str == null) {
			return null;
		}

		// handle negatives
		if (end < 0) {
			end = str.length() + end; // remember end is negative
		}
		if (start < 0) {
			start = str.length() + start; // remember start is negative
		}

		// check length next
		if (end > str.length()) {
			end = str.length();
		}

		// if start is greater than end, return ""
		if (start > end) {
			return "";
		}

		if (start < 0) {
			start = 0;
		}
		if (end < 0) {
			end = 0;
		}

		return str.substring(start, end);
	}

	// Left/Right/Mid
	// -----------------------------------------------------------------------
	/**
	 * <p>
	 * Gets the leftmost <code>len</code> characters of a String.
	 * </p>
	 * 
	 * <p>
	 * If <code>len</code> characters are not available, or the String is
	 * <code>null</code>, the String will be returned without an exception. An
	 * exception is thrown if len is negative.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.left(null, *)    = null
	 * StringUtils.left(*, -ve)     = ""
	 * StringUtils.left("", *)      = ""
	 * StringUtils.left("abc", 0)   = ""
	 * StringUtils.left("abc", 2)   = "ab"
	 * StringUtils.left("abc", 4)   = "abc"
	 * </pre>
	 * 
	 * @param str the String to get the leftmost characters from, may be null
	 * @param len the length of the required String, must be zero or positive
	 * @return the leftmost characters, <code>null</code> if null String input
	 */
	public static String left(String str, int len) {
		if (str == null) {
			return null;
		}
		if (len < 0) {
			return "";
		}
		if (str.length() <= len) {
			return str;
		} else {
			return str.substring(0, len);
		}
	}

	/**
	 * <p>
	 * Gets the rightmost <code>len</code> characters of a String.
	 * </p>
	 * 
	 * <p>
	 * If <code>len</code> characters are not available, or the String is
	 * <code>null</code>, the String will be returned without an an exception.
	 * An exception is thrown if len is negative.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.right(null, *)    = null
	 * StringUtils.right(*, -ve)     = ""
	 * StringUtils.right("", *)      = ""
	 * StringUtils.right("abc", 0)   = ""
	 * StringUtils.right("abc", 2)   = "bc"
	 * StringUtils.right("abc", 4)   = "abc"
	 * </pre>
	 * 
	 * @param str the String to get the rightmost characters from, may be null
	 * @param len the length of the required String, must be zero or positive
	 * @return the rightmost characters, <code>null</code> if null String input
	 */
	public static String right(String str, int len) {
		if (str == null) {
			return null;
		}
		if (len < 0) {
			return "";
		}
		if (str.length() <= len) {
			return str;
		} else {
			return str.substring(str.length() - len);
		}
	}

	/**
	 * check term is exist from src
	 * 
	 * @param src
	 * @param term
	 * @return boolean
	 */
	public static boolean exist(String src, String term) {
		if (src == null || term == null) {
			return false;
		}
		int index = src.indexOf(term);
		return index >= 0;
	}

	/**
	 * encode url
	 * 
	 * @param src
	 * @return String
	 */
	public static String encodeURL(String src) {
		String result = null;
		try {
			result = URLEncoder.encode(src, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * decode url
	 * 
	 * @param src
	 * @return String
	 * @throws UnsupportedEncodingException
	 */
	public static String decodeURL(String src) throws UnsupportedEncodingException {
		return URLDecoder.decode(src, "UTF-8");
	}

	/**
	 * 
	 * @return String
	 */
	public static String format() {
		return format("yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 
	 * @param pattern
	 * @return string
	 */
	public static String format(String pattern) {
		return format(pattern, new Date());
	}

	/**
	 * 
	 * @param pattern
	 * @param date
	 * @return string
	 */
	public static String format(String pattern, Date date) {
		return new SimpleDateFormat(pattern).format(date);
	}

	/**
	 * 
	 * @param pattern
	 * @param text
	 * @return Date
	 */
	public static Date parse(String pattern, String text) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		try {
			return dateFormat.parse(text);
		} catch (ParseException ex) {
			return new Date();
		}
	}

	/**
	 * 
	 * @param str
	 * @param rex
	 * @return boolean
	 */
	public static boolean rexp(String str, String rex) {
		Pattern pattern = Pattern.compile(rex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	/**
	 * 生成UUID
	 * 
	 * @return String
	 * */
	public static String getUUID() {
		String uuid = UUID.randomUUID().toString();
		return uuid.replaceAll("-", "");
	}

	/**
	 * 生成多个UUID
	 * 
	 * @param count
	 *            数量
	 * 
	 * @return String[]
	 * */
	public static String[] getUUID(int count) {
		if (count < 1)
			return null;
		String[] uuid = new String[count];
		for (int i = 0; i < count; i++)
			uuid[i] = getUUID();
		return uuid;
	}

	/**
	 * 获得当前年份
	 * 
	 * @return int
	 */
	public static int getNowYear() {
		Calendar now = Calendar.getInstance();
		return now.get(Calendar.YEAR);
	}

	/**
	 * 获取随机数
	 * 
	 * @param length
	 *            长度
	 * 
	 * @return String
	 */
	public static String getRandomNum(int length) {
		Random rd = new Random(); // 创建随机对象
		String n = "";
		int rdGet; // 取得随机数
		do {
			rdGet = Math.abs(rd.nextInt()) % 10 + 48; // 产生48到57的随机数(0-9的键位值)
			char num1 = (char) rdGet;
			String dd = Character.toString(num1);
			n += dd;

		} while (n.length() < length);// 假如长度小于4
		return n;
	}

	/**
	 * 格式化时间，按照yyyy-MM-dd HH:mm:ss格式
	 * 
	 * @param date
	 *            时间
	 * 
	 * @return String
	 */
	public static String formatDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}

	/**
	 * 格式化时间，按照yyyy-MM-dd格式
	 * 
	 * @param date
	 *            时间
	 * 
	 * @return String
	 */
	public static String formatDateDay(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		return sdf.format(date);
	}

	/**
	 * 请求数据并且获得返回值
	 * 
	 * @param requestUrl
	 *            请求链接
	 * 
	 * @param requestData
	 *            请求参数
	 * 
	 * @param method
	 *            请求方式
	 * 
	 * @param charset
	 *            编码
	 * 
	 * @return String
	 * 
	 * @throws IOException
	 */
	public static String readResponse(String requestUrl, String requestData,
			String method, String charset) throws IOException {
		OutputStreamWriter out = null;
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
			conn.setRequestProperty("Content-Type", "text/html");
			conn.setRequestProperty("Accept-Charset", charset);
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn
					.setRequestProperty("Content-Length", ""
							+ requestData.length());
			out = new OutputStreamWriter(conn.getOutputStream(), charset);
			out.write(requestData);
			out.flush();
			out.close();
			// 获取响应状态
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				System.err.println("connect failed!");
				return "";
			} else {
				// 获取响应内容体
				String line, result = "";
				BufferedReader in = new BufferedReader(new InputStreamReader(
						conn.getInputStream(), charset));
				while ((line = in.readLine()) != null) {
					result += line + "\n";
				}
				return result;
			}
		} catch (SocketException se) {
			se.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (out != null)
				out.close();
		}
	}

	public static String readerText(String filePath) throws IOException {
		File file = new File(filePath);
		String sqlText = new String();
		if (file.exists()) {
			InputStreamReader inputStreamReader = new InputStreamReader(
					new FileInputStream(file));
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str;
			while ((str = bufferedReader.readLine()) != null) {
				sqlText += (str + "\n");
			}
			try {
				bufferedReader.close();
				inputStreamReader.close();
			} catch (Exception excep) {
				excep.printStackTrace();
			}
			return sqlText;
		}
		return null;
	}

	/**
	 * 获取一周列表
	 * 
	 * @return List
	 * 
	 */
	public static List<Map<String, String>> getWeekdayList() {
		String[] weekday = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
		List<Map<String, String>> weekdayList = new ArrayList<Map<String, String>>();
		for (int i = 0; i < weekday.length; i++) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("name", weekday[i]);
			map.put("value", String.valueOf(i + 1));
			map.put("checked", "");
			weekdayList.add(map);
		}
		return weekdayList;
	}

	/**
	 * 日期返回星期几
	 * 
	 * @param date
	 * 
	 * @return int
	 */
	public static int dayOfWeek(String date) {
		try {
			Calendar c = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			c.setTime(dateFormat.parse(date));
			int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
			return dayOfWeek == 0 ? 7 : dayOfWeek;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 取得当前日期是多少周
	 * 
	 * @param date
	 * @return
	 */
	public static int getWeekOfYear(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setMinimalDaysInFirstWeek(7);
		c.setTime(date);

		return c.get(Calendar.WEEK_OF_YEAR);
	}

	/**
	 * 得到某年某周的第一天
	 * 
	 * @param year
	 * @param week
	 * @return
	 */
	public static String getFirstDayOfWeek(int year, int week) {
		Calendar c = new GregorianCalendar();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, Calendar.JANUARY);
		c.set(Calendar.DATE, 1);

		Calendar cal = (GregorianCalendar) c.clone();
		cal.add(Calendar.DATE, week * 7);

		return formatDateDay(getFirstDayOfWeek(cal.getTime()));
	}

	/**
	 * 得到某年某周的最后一天
	 * 
	 * @param year
	 * @param week
	 * @return
	 */
	public static String getLastDayOfWeek(int year, int week) {
		Calendar c = new GregorianCalendar();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, Calendar.JANUARY);
		c.set(Calendar.DATE, 1);

		Calendar cal = (GregorianCalendar) c.clone();
		cal.add(Calendar.DATE, week * 7);

		return formatDateDay(getLastDayOfWeek(cal.getTime()));
	}

	/**
	 * 取得当前日期所在周的第一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getFirstDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
		return c.getTime();
	}

	/**
	 * 取得当前日期所在周的最后一天
	 * 
	 * @param date
	 * @return
	 */
	public static Date getLastDayOfWeek(Date date) {
		Calendar c = new GregorianCalendar();
		c.setFirstDayOfWeek(Calendar.MONDAY);
		c.setTime(date);
		c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
		return c.getTime();
	}

	/**
	 * 对字符串进行格式化
	 * 
	 * @param str
	 *            需要格式化的字符串
	 * @return
	 */
	public static String formatString(String str) {
		if (str == null)
			return "";
		return str.trim();
	}

	/**
	 * 格式化字符串数组
	 * 
	 * @param strArray
	 *            需要格式化的字符串数组
	 * @return
	 */
	public static String[] formatStringArray(String[] strArray) {
		if (strArray == null || strArray.length == 0)
			return new String[] {};
		for (String string : strArray) {
			string = formatString(string);
		}
		return strArray;
	}
	   
    /**
     * MD5
     * 
     * @param message
     * @return
     */
	public static String GetMD5(String message, String encode) {
		String md5 = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(message.getBytes(encode));
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.toUpperCase().substring(1, 3));
			}
			md5 = sb.toString();
		} catch (Exception e) {
		}
		return md5;
	}
    public static String GetMD5(byte[] message, String encode) {
        String md5 = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(message);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; i++) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .toUpperCase().substring(1, 3));
            }
            md5 = sb.toString();
        } catch (Exception e) {
        }
        return md5;
    }
    
    /**  
     * 字符串转换成十六进制字符串 
     * @param String str 待转换的ASCII字符串 
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B] 
     */    
    public static String str2HexStr(String str)  
    {    
  
        char[] chars = "0123456789ABCDEF".toCharArray();    
        StringBuilder sb = new StringBuilder("");  
        byte[] bs = str.getBytes();    
        int bit;    
          
        for (int i = 0; i < bs.length; i++)  
        {    
            bit = (bs[i] & 0x0f0) >> 4;    
            sb.append(chars[bit]);    
            bit = bs[i] & 0x0f;    
            sb.append(chars[bit]);  
            sb.append(' ');  
        }    
        return sb.toString().trim();    
    }  
      
    /**  
     * 十六进制转换字符串 
     * @param String str Byte字符串(Byte之间无分隔符 如:[616C6B]) 
     * @return String 对应的字符串 
     */    
    public static String hexStr2Str(String hexStr)  
    {    
        String str = "0123456789ABCDEF";    
        char[] hexs = hexStr.toCharArray();    
        byte[] bytes = new byte[hexStr.length() / 2];    
        int n;    
  
        for (int i = 0; i < bytes.length; i++)  
        {    
            n = str.indexOf(hexs[2 * i]) * 16;    
            n += str.indexOf(hexs[2 * i + 1]);    
            bytes[i] = (byte) (n & 0xff);    
        }    
        return new String(bytes);    
    }  
      
    /** 
     * bytes转换成十六进制字符串 
     * @param byte[] b byte数组 
     * @return String
     */  
    public static String byte2HexStr(byte[] b)  
    {  
        String stmp="";  
        StringBuilder sb = new StringBuilder("");  
        for (int n=0;n<b.length;n++)  
        {  
            stmp = Integer.toHexString(b[n] & 0xFF);  
            sb.append((stmp.length()==1)? "0"+stmp : stmp);  
//            sb.append(" ");  
        }  
        return sb.toString().toLowerCase().trim();  
    }  
      
    /** 
     * bytes字符串转换为Byte值 
     * @param String src Byte字符串，每个Byte之间没有分隔符 
     * @return byte[] 
     */  
    public static byte[] hexStr2Bytes(String src)  
    {  
        int m=0,n=0;  
        int l=src.length()/2;  
        System.out.println(l);  
        byte[] ret = new byte[l];  
        for (int i = 0; i < l; i++)  
        {  
            m=i*2+1;  
            n=m+1;  
            ret[i] = Byte.decode("0x" + src.substring(i*2, m) + src.substring(m,n));  
        }  
        return ret;  
    }  
  
    /** 
     * String的字符串转换成unicode的String 
     * @param String strText 全角字符串 
     * @return String 每个unicode之间无分隔符 
     * @throws Exception 
     */  
    public static String strToUnicode(String strText)  
        throws Exception  
    {  
        char c;  
        StringBuilder str = new StringBuilder();  
        int intAsc;  
        String strHex;  
        for (int i = 0; i < strText.length(); i++)  
        {  
            c = strText.charAt(i);  
            intAsc = (int) c;  
            strHex = Integer.toHexString(intAsc);  
            if (intAsc > 128)  
                str.append("\\u" + strHex);  
            else // 低位在前面补00  
                str.append("\\u00" + strHex);  
        }  
        return str.toString();  
    }  
      
    /** 
     * unicode的String转换成String的字符串 
     * @param String hex 16进制值字符串 （一个unicode为2byte） 
     * @return String 全角字符串 
     */  
    public static String unicodeToString(String hex)  
    {  
        int t = hex.length() / 6;  
        StringBuilder str = new StringBuilder();  
        for (int i = 0; i < t; i++)  
        {  
            String s = hex.substring(i * 6, (i + 1) * 6);  
            // 高位需要补上00再转  
            String s1 = s.substring(2, 4) + "00";  
            // 低位直接转  
            String s2 = s.substring(4);  
            // 将16进制的string转为int  
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);  
            // 将int转换为字符  
            char[] chars = Character.toChars(n);  
            str.append(new String(chars));  
        }  
        return str.toString();  
    } 
    
    /** 
     * Read bytes from a File into a byte[].
     * 
     * @param file The File to read.
     * @return A byte[] containing the contents of the File.
     * @throws IOException Thrown if the File is too long to read or couldn't be read fully.
     */
	public static byte[] readBytesFromFile(String filePath) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			throw new IOException("file not exists:" + filePath);
		}

		InputStream is = new FileInputStream(file);

		try {
			// Get the size of the file
			long length = file.length();

			// You cannot create an array using a long type. It needs to be an int type.
			// Before converting to an int type, check to ensure that file is not larger than Integer.MAX_VALUE.
			if (length > Integer.MAX_VALUE) {
				throw new IOException("Could not completely read file "
						+ file.getName() + " as it is too long (" + length
						+ " bytes, max supported " + Integer.MAX_VALUE + ")");
			}

			// Create the byte array to hold the data
			byte[] bytes = new byte[(int) length];

			// Read in the bytes
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length
					&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}

			// Ensure all the bytes have been read in
			if (offset < bytes.length) {
				throw new IOException("Could not completely read file " + file.getName());
			}

			return bytes;
		} catch (Exception e) {
			e.printStackTrace();

			return null;
		} finally {
			// Close the input stream and return bytes
			is.close();
		}

	}
    
    /**
     * Writes the specified byte[] to the specified File path.
     * 
     * @param theFile filePath representing the path to write to.
     * @param bytes The byte[] of data to write to the File.
     * @throws IOException Thrown if there is problem creating or writing the File.
     */
	public static void writeBytesToFile(String theFile, byte[] bytes) throws IOException {
		BufferedOutputStream bos = null;

		try {
			FileOutputStream fos = new FileOutputStream(theFile);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} finally {
			if (bos != null) {
				try {
					// flush and close the BufferedOutputStream
					bos.flush();
					bos.close();
				} catch (Exception e) {
				}
			}
		}
	}
	
	public static String trace(Exception e) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        e.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        return buffer.toString();
    }

}
